import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:yysk_app/model/pay_model/bill_page_model.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/bill_detail/bill_detail_date_filter_dialog.dart';

class SettleDetailModel {
  final String type;
  final String time;
  final double amount;
  final double balance;
  SettleDetailModel({
    required this.type,
    required this.time,
    required this.amount,
    required this.balance,
  });
}

class SettleDetailController extends GetxController {
  var selectedDateRange = '时间筛选'.obs;
  var startDate = DateTime.now().obs;
  var endDate = DateTime.now().obs;
  final activeTab = 'PROCESSING'.obs;

  var settleList = <SettleDetailModel>[].obs;
  var filteredList = <SettleDetailModel>[].obs;

  final ScrollController scrollController = ScrollController();

  var type = '1'.obs; //1个人，2企业,3个体工商户
  var channel = 'DIN_PAY'.obs; //支付类型 //HUIFU汇付
  var startTime = null;
  var endTime = null;
  int pageNum = 1;
  int pageSize = 20;
  var billList = RxList<BillPageItem>([]);
  @override
  void onInit() {
    super.onInit();

    type.value = Get.parameters['type'] ?? Get.arguments['type'];
    channel.value = Get.parameters['channel'] ?? Get.arguments['channel'];
    getBillList();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getBillList(loadMore: true);
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }

  Future<void> getBillList({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }
    final now = DateTime.now();
    // 计算三个月前的年/月
    int year = now.year;
    int month = now.month - 3;

    // 处理跨年逻辑（如 1月减 3个月 → 去年 10月）
    if (month < 1) {
      month += 12;
      year -= 1;
    }
    final threeMonthsAgo = DateTime(year, month, now.day);
    final endTime2 = DateTime.now();
    var params = {
      'pageNum': pageNum,
      'pageSize': pageSize,
      'accountType':
          type.value == '1'
              ? 'USER'
              : (type.value == '2' ? 'ENTERPRISE' : 'INDIVIDUAL_BUSINESS'),
      "startTime": startTime ?? threeMonthsAgo.toString(),
      "endTime": endTime ?? endTime2.toString(),
      "type": 'SPLIT',
      "status": activeTab.value,
      "channel": channel.value,
    };

    try {
      await http.netFetch<BillPageModel>(
        PayUrl.billPage,
        params: params,
        success: (result) {
          List<BillPageItem> list = result.data?.list ?? [];
          if (loadMore && list.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            billList.clear();
          }
          billList.addAll(list);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
    }
  }

  changeTab(String code) {
    if (code == activeTab.value) {
      return;
    }
    activeTab.value = code;
    print('${code}');
    getBillList();
  }

  void showDateFilter() async {
    var result = await showDateFilterDialog(
      context: Get.context!,
      start: startDate.value,
      end: endDate.value,
    );
    if (result is List<DateTime> && result.length == 2) {
      startDate.value = result[0];
      endDate.value = result[1];
      selectedDateRange.value =
          '${startDate.value.year}年${startDate.value.month}月${startDate.value.day}日 - ${endDate.value.year}年${endDate.value.month}月${endDate.value.day}日';
      startTime =
          '${startDate.value.year}-${startDate.value.month < 10 ? '0${startDate.value.month}' : startDate.value.month}-${startDate.value.day} 00:00:00';
      endTime =
          '${endDate.value.year}-${endDate.value.month < 10 ? '0${endDate.value.month}' : endDate.value.month}-${endDate.value.day} 23:59:59';
      getBillList();
    }
  }

  void filterList() {
    filteredList.value = settleList;
  }
}
